package 链表算法题;

public class 移除链表元素 {
    class Solution{
        //设置虚拟点的做法
        public ListNode removeElements(ListNode head ,int val){
            if (head==null) return null;
            //设置虚拟结点
            ListNode dummy = new ListNode(-1,head);
            ListNode pre = dummy;
            ListNode curr = head;
            while(curr!=null){
                if (curr.val == val){
                    pre.next = curr.next;
                }else {
                    pre = curr;
                }
                curr = curr.next;
            }
            return dummy.next;
        }

        //不设点
        public ListNode removeElements2(ListNode head , int val){
            if (head!=null&&head.val==val){
                head = head.next;
            }
            //已经为空 提前退出
            if (head == null){
                return null;
            }
            ListNode pre = head;
            ListNode cur = head.next;
            while (cur != null) {
                if (cur.val == val) {
                    pre.next = cur.next;
                } else {
                    pre = cur;
                }
                cur = cur.next;
            }
            return head;
        }
    }
}
